package sky.wechat_tools.util;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class WxConfig {
	private static final String configFile = "/wx.properties";
	private static WxConfig config = null;

	private volatile String appId;
	private volatile String appSecret;
	private volatile String token;
	private volatile String aesKey;
	private volatile String mchId;
	private volatile String apiKey;

	private volatile String accessToken;
	private volatile Long expiresTime;


	private WxConfig() {
		Properties p = new Properties();
		InputStream inStream = this.getClass().getResourceAsStream(configFile);
		if(inStream == null){
			System.out.println("读取配置文件失败");
		}
		try {
			p.load(inStream);
			this.appId = p.getProperty("wx.appId");
            if(StringUtils.isNotBlank(this.appId)){
            	this.appId = this.appId.trim();
            }
            this.appSecret = p.getProperty("wx.appSecret");
            if(StringUtils.isNotBlank(this.appSecret)){
            	this.appSecret = this.appSecret.trim();
            }
            this.token = p.getProperty("wx.token");
            if(StringUtils.isNotBlank(this.token)) {
				this.token = this.token.trim();
			}
			this.aesKey = p.getProperty("wx.aesKey");
            if(StringUtils.isNotBlank(this.aesKey)) {
				this.aesKey = this.aesKey.trim();
			}
            this.mchId = p.getProperty("wx.mchId");
            if(StringUtils.isNotBlank(this.mchId)){
            	this.mchId = this.mchId.trim();
			}
            this.apiKey = p.getProperty("wx.apiKey");
            if(StringUtils.isNotBlank(this.apiKey)){
            	this.apiKey = this.apiKey.trim();
			}
			inStream.close();
			this.expiresTime = 0L;

		} catch (IOException e) {
			System.out.println(e);
		}
		System.out.println("load wx.properties success");
	}

	public static synchronized WxConfig getInstance(){
		if(config == null){
			config = new WxConfig();
		}
		return config;
	}
	
	public String getAccessToken() {
		return accessToken;
	}
	
	public boolean isAccessTokenExpired() {
		return System.currentTimeMillis() > this.expiresTime;
	}

	public void expireAccessToken()
	{
		this.expiresTime = 0L;
	}

	public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
		this.accessToken = accessToken;
		this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
	}
	public String getToken() {
		return token;
	}
}

